<template>
	<view class="container">
		<image class="bg-image" src="@/static/bg/blue.jpg"/>
		<image src="@/static/logo.png" alt="" class="logo"/>
		<view class="title">密码本</view>
		<!--如果已经设置密码-->
		<view class="password-view" v-if="settingPassword">
			<image src="@/static/icon/lock-white.png"></image>
			<input
				   type="password"
				   v-model="password"
				   class="password"
				   placeholder-class="placeholder"
				   placeholder="登录密码"
				   @input="login"/>
		</view>

		<!--如果未设置密码-->
		<view v-else>
			<view class="password-view">
				<image src="@/static/icon/lock-white.png"></image>
				<input type="password"
					   v-model="newPassword"
					   class="password"
					   placeholder="设置密码"
					   placeholder-class="placeholder">
			</view>
			<view class="password-view">
				<image src="@/static/icon/lock-white.png"></image>
				<input type="password"
					   v-model="confirmPassword"
					   class="password"
					   placeholder="确认密码"
					   placeholder-class="placeholder">
			</view>
			<button class="login" @click="confirm">确定</button>
		</view>
	</view>
</template>

<script>
import md5 from 'js-md5';
	export default {
		name: "Login",
		data() {
			return {
				// 密码
				password: '',
				// 新密码
				newPassword: '',
				// 确认密码
				confirmPassword: '',
				// 已设置的密码
				settingPassword: null
			};
		},
		created() {
			// 获取已设置的密码
			let password = uni.getStorageSync('password');
			if (password && password !== '') {
				this.settingPassword = password;
			}
		},
		methods: {
			/**
			 * 设置密码
			 */
			confirm() {
				if (this.newPassword === '') {
					this.$u.toast('请设置密码');
					return;
				}
				if (this.newPassword !== this.confirmPassword) {
					this.$u.toast('密码不一致');
					return;
				}
				uni.setStorageSync('password', md5(this.newPassword));
				this.settingPassword = md5(this.newPassword);
				this.$u.toast('设置成功');
			},

			/**
			 * 进行登录
			 */
			login() {
				if (md5(this.password) === this.settingPassword) {
					uni.switchTab({
						url: '/pages/home/home'
					});
				}
			}
		}
	}
</script>

<style scoped>
.container {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
}
.bg-image {
	position: absolute;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	z-index: -1;
}
.logo {
	width: 150px;
	height: 150px;
	margin: 50px auto;
	display: block;
}
.password-view {
	display: flex;
	width: 250px;
	border-bottom: 1px solid white;
	margin: 0 auto;
	align-items: center;
}
.password-view image {
	width: 20px;
	height: 20px;
}
.password {
	background-color: rgba(0, 0, 0, 0);
	outline: none;
	padding: 10px 5px;
	font-size: 15px;
	color: white;
	text-align: left;
}
.placeholder {
	color: #eeeeee;
}
.title {
	color: white;
	font-size: 20px;
	margin-bottom: 30px;
	text-align: center;
}
.login {
	display: block;
	width: 260px;
	height: 40px;
	line-height: 40px;
	margin: 40px auto;
	border-radius: 20px;
	border-width: 0;
	background-color: #a4dbff;
	color: white;
	font-size: 17px;
}
</style>
